package cn.com.cym.gamezao.service.xmu.impl;

import cn.com.cym.gamezao.base.BaseImpl;
import cn.com.cym.gamezao.base.BaseRepository;
import cn.com.cym.gamezao.base.ResultResponse;
import cn.com.cym.gamezao.base.SearchPage;
import cn.com.cym.gamezao.dto.RecruitSearchDto;
import cn.com.cym.gamezao.entity.authorize.User;
import cn.com.cym.gamezao.entity.authorize.UserInfo;
import cn.com.cym.gamezao.entity.xmu.Recruit;
import cn.com.cym.gamezao.entity.xmu.Schedule;
import cn.com.cym.gamezao.enums.UserType;
import cn.com.cym.gamezao.exception.BaseException;
import cn.com.cym.gamezao.jwt.RequestUser;
import cn.com.cym.gamezao.repository.xmu.RecruitRepository;
import cn.com.cym.gamezao.repository.xmu.recruit.CertificateRepository;
import cn.com.cym.gamezao.repository.xmu.recruit.LearnExperienceRepository;
import cn.com.cym.gamezao.repository.xmu.recruit.WorkExperienceRepository;
import cn.com.cym.gamezao.service.authorize.UserInfoService;
import cn.com.cym.gamezao.service.xmu.RecruitService;
import cn.com.cym.gamezao.util.CommonUtils;
import cn.hutool.core.util.ReflectUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@AllArgsConstructor
@Service
@Transactional(rollbackFor = Exception.class)
public class RecruitImpl extends BaseImpl<Recruit> implements RecruitService {

    final RecruitRepository thisRepository;
    final EntityManager entityManager;
    final UserInfoService userInfoService;

    @Override
    public BaseRepository<Recruit, Long> getJpaRepository() {
        return thisRepository;
    }

    @Override
    public Page<Recruit> findByPageable(SearchPage searchPage) {
        String[] sortBy = searchPage.getSortBy().toArray(new String[searchPage.getSortBy().size()]);
        Pageable pageable = PageRequest.of(searchPage.getCurrent()-1, searchPage.getPageSize(), searchPage.getSort(), sortBy);
        Specification<Recruit> specification = new Specification<>() {
            private static final long serialVersionUID = -2661077778894635593L;
            @SneakyThrows
            @Override
            public Predicate toPredicate(Root<Recruit> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                final Map<String, Field> fieldMap = ReflectUtil.getFieldMap(Recruit.class);
                return cb.and(CommonUtils.pageSet(fieldMap,searchPage,cb,root));
            }
        };
        return this.thisRepository.findAll(specification, pageable);
    }

    @Override
    public List<Recruit> search(RecruitSearchDto searchDto) {
        return thisRepository.findByCardTypeAndCardNo(searchDto.getCardType(),searchDto.getCardNo());
    }

    @Override
    public Recruit submit(Recruit recruit) {
        //recruit.setApplyDate(LocalDate.now());
        return this.thisRepository.save(recruit);
    }

    // 当前用户保存自己信息
    @Override
    public Recruit saveByCurrentUser(Recruit recruit) {
        User user = RequestUser.get();
        // 根据当前登入人员查看数据是否存在
        List<Recruit> recruits = this.thisRepository.findByUser(user);
        if(recruits.size()>0 && !recruits.get(0).getId().equals(recruit.getId())){
            throw new BaseException("无权限修改他人数据，请重新登录",new ResultResponse("无权限修改他人数据，请重新登录",403));
        }
        recruit.setUser(user);
        if(recruit.getId()==null){
            recruit.setCreateTime(LocalDateTime.now()).setModifyTime(LocalDateTime.now());
        }
        if(recruit.getCreateTime()==null){
            recruit.setCreateTime(LocalDateTime.now());
        }
        recruit.setModifyTime(LocalDateTime.now());
        this.thisRepository.save(recruit);

        //保存userInfo数据

        UserInfo userInfoByUser = userInfoService.getUserInfoByUser(user);
        // 赋值
        userInfoByUser.setCardType(recruit.getCardType()).setCardCode(recruit.getCardNo())
                .setBirthDate(recruit.getBirthDate()).setName(recruit.getName())
                        .setSex(recruit.getSex());
        userInfoService.save(userInfoByUser);
        return recruit;
    }

    @Override
    public Recruit getByCurrentUser() {
        User user = RequestUser.get();
        final List<Recruit> byUser = this.thisRepository.findByUser(user);
        return byUser.size()<1?null:byUser.get(0);
    }

    @Override
    public Recruit getById(Long id) {
        return thisRepository.getById(id);
    }

    @Override
    public Page<Recruit> findByPageableAndUserType(SearchPage searchPage, UserType userType) {
        String[] sortBy = searchPage.getSortBy().toArray(new String[searchPage.getSortBy().size()]);

        Pageable pageable = PageRequest.of(searchPage.getCurrent()-1, searchPage.getPageSize(), searchPage.getSort(), sortBy);
        //thisRepository.findAll(Example,pageable);
        return null;
    }

    @Override
    public Recruit save(Recruit recruit) {
        return super.save(recruit);
    }
}
